package network.tcp.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * @program: bio
 * @description:
 * @author: zhanghz001
 * @create: 2020-10-27 11:10
 **/
public class NioClient {
    public static void main(String[] args) {
        try {
            //打开通道
            SocketChannel channel = SocketChannel.open();

            // 不能  不能 不能 设置成false  不然会导致发送不成功
            // channel.configureBlocking(false);

            //绑定ip和端口
            channel.connect(new InetSocketAddress("localhost", 10000));

            //写数据
            ByteBuffer buffer = ByteBuffer.wrap("客户端发送消息了".getBytes());

            channel.write(buffer);
            channel.shutdownOutput();
            System.out.println("==========");

            //读到服务器写会的数据
            ByteBuffer dst = ByteBuffer.allocate(1024);
            int len;
            while ((len = channel.read(dst)) > 0) {
                dst.flip();
                System.out.println(new String(dst.array(), 0, len));
                dst.clear();
            }

            //释放资源
            channel.close();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
    }
}
